package com.alipay.app.groupmeal.standard.ui.c.abcp;

import static com.alipay.app.groupmeal.standard.constant.ConfigConstant.onOffLine;

import android.app.Activity;
import android.content.Intent;
import android.view.KeyEvent;

import com.alipay.app.groupmeal.standard.R;
import com.alipay.app.groupmeal.standard.base.BaseMVCActivity;
import com.alipay.app.groupmeal.standard.bean.AliPayResVo;
import com.alipay.app.groupmeal.standard.constant.SystemConsts;
import com.alipay.app.groupmeal.standard.event.EventManager;
import com.alipay.app.groupmeal.standard.http.bean.resp.Result;
import com.alipay.app.groupmeal.standard.offline.bean.FkBean;
import com.alipay.app.groupmeal.standard.offline.bean.OrderBean;
import com.alipay.app.groupmeal.standard.offline.manager.FkBeanManager;
import com.alipay.app.groupmeal.standard.offline.manager.OrderDataManager;
import com.alipay.app.groupmeal.standard.ui.b.PayingPre;
import com.alipay.app.groupmeal.standard.ui.b.util.WIth;
import com.alipay.sdk.abcphaima.AbcpHM;
import com.alipay.sdk.abcphaima.AbcpHMLoadingPage;
import com.alipay.sdk.abcphaima.bean.PageResultData;
import com.alipay.sdk.util.LogUtil;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.internal.observers.BlockingBaseObserver;

public class CPayAbcpActivity extends BaseMVCActivity {

    public static CPayAbcpActivity payActivity = null;
    private String mTradeNo;

    private String mSessionId;
    private PayingPre payingPre;
    private String amount;
    public static final String AMOUNT = "amount";


    public static void startActAbcp(Activity activity, String amount) {
        //自我启动，带上金额
        Intent intent = new Intent(activity, CPayAbcpActivity.class);
        intent.putExtra(AMOUNT, amount);
        activity.startActivity(intent);
    }

    @Override
    public boolean onKeyEventBack(KeyEvent event) {
        finish();
        return super.onKeyEventBack(event);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_transparent;
    }

    @Override
    protected void initView() {
        payActivity = this;
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        amount = intent.getStringExtra(AMOUNT);
        mTradeNo = "ICZF" + new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.CHINA).format(new Date());
    }

    @Override
    protected void dissmissPresnetation() {
        if (payingPre != null) {
            payingPre.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        payActivity = null;

    }

    @Override
    public void initPresentation() {
        super.initPresentation();
        if (mDisplay != null) {
            payingPre = new PayingPre(this, mDisplay);
            registerPresentation(payingPre);
            showPresentation(payingPre);
//            //显示支付中金额
            payingPre.showPaying(amount);
        }
        //abcp刷脸服务
        abcp();
    }

    private void abcp() {
        AbcpHMLoadingPage.showPage("正在支付..请稍后", new AbcpHM.AbcpLoadingCallback() {
            @Override
            public void onSuccess(String tradeNo, String sessionId, String alipayUid) {
                LogUtil.d(tradeNo);
                mSessionId = sessionId;
                toPay();
            }

            @Override
            public void onFail(String code, String msg) {
                LogUtil.d("失败回调");
                EventBus.getDefault().post(new EventManager.clearAmount());
                finish();
            }

            @Override
            public void onEvent(String sessionId) {
                LogUtil.d("onEvent回调");
            }
        });

    }

    private void toPay() {
        //脱机模式下，先插入订单记录，后期上传

        if (!onOffLine) {
            //脱机交易模式
            FkBean fkBean = FkBeanManager.getInstance().getFkByCardSn(SystemConsts.getSystemConsts().getCardSn());
            if (fkBean == null) {
                toResult(2, "", amount,
                        mTradeNo, mSessionId, "", false,
                        0, "1", "非法卡");
                return;

            } else if (new BigDecimal(amount).compareTo(new BigDecimal(fkBean.getKye())) == -1) {
                OrderBean orderBean = new OrderBean();
                orderBean.setSuccess(true);//在线模式，订单为未知状态，则不是成功状态
                orderBean.setHavePost(false);//在线模式，订单服务器上操作，则表示为上传订单
                orderBean.setAmount(amount);
                orderBean.setTradeNo(mTradeNo);
                orderBean.setCreateTime(new Date());
                orderBean.setCardno(fkBean.getCardno());
                orderBean.setUserName(fkBean.getName());
                OrderDataManager.getInstance().insert(orderBean);
                toResult(2, "", amount,
                        mTradeNo, mSessionId, "", true,
                        0, "1", "支付成功");
            } else {
                toResult(2, "", amount,
                        mTradeNo, mSessionId, "", true,
                        0, "1", "余额不足");
            }
            return;
        }


        //发起网络消费,需要检查是否脱机支付,脱机支付另外方案
        OrderBean orderBean = new OrderBean();
        orderBean.setSuccess(false);//在线模式，订单为未知状态，则不是成功状态
        orderBean.setHavePost(true);//在线模式，订单服务器上操作，则表示为上传订单
        orderBean.setAmount(amount);
        orderBean.setTradeNo(mTradeNo);
        orderBean.setCreateTime(new Date());
        OrderDataManager.getInstance().insert(orderBean);
        if(cache.getIfPresent(SystemConsts.getSystemConsts().getCardSn()) != null) {
            return;
        }
        cache.put(SystemConsts.getSystemConsts().getCardSn(), String.valueOf(System.currentTimeMillis()));
        new WIth(this).cardPay(amount, SystemConsts.getSystemConsts().getCardSn(),
                mTradeNo, mSessionId, new BlockingBaseObserver<Result<AliPayResVo>>() {
                    @Override
                    public void onNext(@NonNull Result<AliPayResVo> stringResult) {
                        AliPayResVo aliPayResVo = stringResult.getResult();
                        toResult(2, "", aliPayResVo.getAmount(),
                                aliPayResVo.getTradeNo(), aliPayResVo.getSessionId(), "", aliPayResVo.isSuccess(),
                                aliPayResVo.getIsFailType(), aliPayResVo.getFailCode(), aliPayResVo.getMsg());
                        if (aliPayResVo.isSuccess()) {
                            //支付成功订单，需要更改标志，并存入数据库
                            orderBean.setCardno(aliPayResVo.getFk().getCardno());
                            orderBean.setUserName(aliPayResVo.getFk().getName());
                            orderBean.setSuccess(true);
                            OrderDataManager.getInstance().update(orderBean);
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }
                });

    }

    private void toResult(int type, final String authCode, String amount,
                          final String tradeNo, final String sessionId, String buyerLogonId,
                          boolean isSuccess, int isFailType, String failCode, String msg) {
        PageResultData pageResultData = new PageResultData();
        pageResultData.success = isSuccess;
        if (isSuccess) {
            pageResultData.buyerLogonId = buyerLogonId;
        } else {
            pageResultData.failCode = failCode;
            pageResultData.message = msg;
        }
        pageResultData.totalAmount = amount;
        pageResultData.paidAmount = amount;
        pageResultData.authCode = authCode;
        pageResultData.tradeNo = tradeNo;
        pageResultData.sessionId = sessionId;
        pageResultData.type = type;
        CPayResultAbcpActivity.startAct(this, pageResultData);
    }

}
